package web.eshop.panels;

import domain.Comment;
import domain.shop.Product;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.*;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.customer.ShopCustomerService;
import web.eshop.CommentBean;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class CommentsPanel extends ShopBasePanel {

    @SpringBean
    private ShopCustomerService shopCustomerService;
    private static Logger logger = Logger.getLogger(CommentsPanel.class.getName());

    public CommentsPanel(String id, final IModel<Product> productModel) {
        super(id);

        final WebMarkupContainer commentListContainer = new WebMarkupContainer("commentListContainer");
        commentListContainer.setOutputMarkupId(true);

        CommentListModel commentListModel = new CommentListModel(productModel.getObject().getId());
        final ListView<Comment> commentList = new ListView<Comment>("commentList", commentListModel) {

            @Override
            protected void populateItem(final ListItem<Comment> item) {
                item.add(new Label("name", new PropertyModel(item.getModel(), "name")));
                item.add(new Label("comment", new PropertyModel(item.getModel(), "comment")));
                item.add(new Label("timestamp", new PropertyModel(item.getModel(), "timestamp")));
            }
        };
        commentListContainer.add(commentList);
        add(commentListContainer);

        final Label noComments = new Label("noComments", "No Comments") {

            @Override
            public boolean isVisible() {
                return commentList.size() == 0;
            }
        };
        noComments.setOutputMarkupId(true);
        add(noComments);

        CompoundPropertyModel<CommentBean> model = new CompoundPropertyModel<CommentBean>(new CommentBean());
        final Form form = new Form<CommentBean>("commentForm", model) {
            @Override
            public void onSubmit() {
                super.onSubmit();
                CommentBean commentBean = (CommentBean) this.getModelObject();
                if (commentBean.getConfirmEmail() != null) {
                    error("spam");
                    return;
                }

                if (!commentBean.passCheck()) {
                    error(getLocalizer().getString("comment.fail.password", this));
                    commentBean.invalidate();
                    return;
                }
                Product product = productModel.getObject();
                Comment comment = new Comment();
                comment.setProduct(product);
                comment.setName(commentBean.getName());
                comment.setEmail(commentBean.getEmail());
                comment.setComment(commentBean.getComment());
                String ipAddress =
                        ((WebRequest) getRequest()).getHttpServletRequest().getRemoteAddr();
                comment.setIpAddress(ipAddress);
                try {
                    shopCustomerService.saveComment(comment);
                    commentBean.clear();
                    info(getLocalizer().getString("comment.success.added", this));
                    setRedirect(true);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    error(getLocalizer().getString("system.error", this));
                }

            }
        };
        add(form);

        WebMarkupContainer container = new WebMarkupContainer("captchaPassword");

        if (WebApplication.DEVELOPMENT.equalsIgnoreCase(WebApplication.get().getConfigurationType())) {
            container.add(new Label("password", new Model(model.getObject().getImagePass())));
        } else {
            container.setVisible(false);
        }


        form.add(container);

        RequiredTextField<String> commentName = new RequiredTextField<String>("name");
        commentName.setOutputMarkupId(true);
        form.add(commentName);

        RequiredTextField<String> commentEmail = new RequiredTextField<String>("email");
//        commentEmail.add(EmailAddressValidator.getInstance());
        commentEmail.setOutputMarkupId(true);
        form.add(commentEmail);

        TextField<String> commentConfirmEmail = new TextField<String>("confirmEmail");
        commentConfirmEmail.setOutputMarkupId(true);
        form.add(commentConfirmEmail);

        final Image captchaImage = new Image("captchaImage", new PropertyModel(form.getModel(), "captchaImage"));


        captchaImage.setOutputMarkupId(true);
        form.add(captchaImage);

        TextField<String> password = new TextField<String>("password");
        password.setOutputMarkupId(true);
        form.add(password);


        TextArea<String> commentComment = new TextArea<String>("comment");
        commentComment.setRequired(true);
        commentComment.setOutputMarkupId(true);
        form.add(commentComment);


    }

    private class CommentListModel extends LoadableDetachableModel<List<Comment>> {

        private Long productId;

        public CommentListModel(Long productId) {
            this.productId = productId;
        }

        @Override
        protected List<Comment> load() {
            return shopCustomerService.findCommentsByProductId(productId);
        }
    }
}
